package dao

import (
	"fmt"
	"time"

	"cron-go/internal/pkg/crontab/models"
	"cron-go/internal/pkg/database/mysql"

	"github.com/go-liam/util/conv"
	"github.com/go-liam/util/response"
)

var LogDaoServer = new(LogDao)

type LogDao struct {
}

func (e *LogDao) FindOneByTaskID(taskID int64) (*models.TaskLogMysqlModel, error) {
	item := new(models.TaskLogMysqlModel)
	sql := "select * from cron_task_log where task_id =?  and is_delete = 0 limit 1 "
	v := mysql.GetDB(mysql.DB_NAME).Raw(sql, taskID).Scan(item)
	return item, v.Error
}

func (e *LogDao) FindOneByID(id int64) (*models.TaskLogMysqlModel, error) {
	item := new(models.TaskLogMysqlModel)
	sql := "select * from cron_task_log where id =?  limit 1 "
	v := mysql.GetDB(mysql.DB_NAME).Raw(sql, id).Scan(item)
	return item, v.Error
}

func (e *LogDao) Create(item *models.TaskLogMysqlModel) (int64, error) {
	item.CreatedAt = time.Now().Unix()
	item.Date = conv.TimeNowFormat("2006-01-02")
	v := mysql.GetDB(mysql.DB_NAME).Create(item)
	return v.RowsAffected, v.Error
}

func (e *LogDao) FindMulti(p *response.Pagination, s *response.ListParameter) ([]*models.TaskLogMysqlModel, error) {
	var result []*models.TaskLogMysqlModel
	sqlLimit := fmt.Sprintf(" limit %d , %d  ", (p.Current-1)*p.PageSize, p.PageSize)
	sqlWhere := "  " + s.WhereSt
	sql := "select * from cron_task_log where " + sqlWhere + s.OrderSt + sqlLimit
	mysql.GetDB(mysql.DB_NAME).Model(&models.TaskLogMysqlModel{}).Where(sqlWhere).Count(&p.Total)
	v := mysql.GetDB(mysql.DB_NAME).Raw(sql).Scan(&result)
	return result, v.Error
}

func (e *LogDao) Clear() (int64, error) {
	date := time.Now().Unix() - 1*60*60*24 //100*60*60*24
	sql := fmt.Sprintf(" delete from `cron_task_log` where `id` > 0 and `created_at` < %v ; ", date)
	println(sql)
	v := mysql.GetDB(mysql.DB_NAME).Exec(sql)
	return v.RowsAffected, v.Error
}
